define(
	[
		'require',
		'broada/ui/dialog',
		"apm/ui/grid",
		'apm/ui/business_time_ranges',
		'broada/base/text!../tpls/business_trades.hbs',
		'apm/ui/business_tradesAllSelect'
	],
	function(require){
		var tpl = require('broada/base/text!../tpls/business_trades.hbs');

		var BusinessConfigThresholdComponent = Ember.Component.extend({
			TimeRanges: require('apm/ui/business_time_ranges'),

			TradesAllSelect : require('apm/ui/business_tradesAllSelect'),

			layout: Ember.HTMLBars.compile(tpl),

			clickTimeChange: Ember.observer('clickTimePoint', function(){
				var view = Broada.getView("businessTimeRangesTopo");
				if(this.get("clickTimePoint") != null){
					var date = new Date(this.get("clickTimePoint"));
					if(typeof view != "undefined"){
						var range = view.getTimeRange().endDate - view.getTimeRange().startDate;
						if(range == 60000){
							this.set("startDate", date);
							this.set("endDate", new Date(date.getTime()+range));
						}else{
							this.set("startDate", new Date(date-range));
							this.set("endDate", date);
						}
					}
					typeof view != "undefined"?view.set("btnTxt", date?APM.util.formatDate(date, "f"):null):null;
					this.requirePerformances();
				}
			}),

			tradesAllbtnTxtChange: Ember.observer('tradesAllbtnTxt', function(){
				var btn = this.get('tradesAllbtnTxt');
				if(btn == "请选择业务组件"){
					this.set("tradeIp",null);
					this.set("tradeProto",null);
					this.requirePerformances();
				}else{
					if(btn.split(":").length > 1){
						this.set("tradeIp",btn.split(":")[0]);
						this.set("tradeProto",btn.split(":")[1]);
					}else{
						var re=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
						if(re.test(btn)){
							this.set("tradeIp",btn);
							this.set("tradeProto",null);
						}else{
							this.set("tradeIp",null);
							this.set("tradeProto",btn);
						}
					}
					this.requirePerformances();
				}
			}),

			Dialog: require('broada/ui/dialog'),

			Grid: require("apm/ui/grid"),

			dialogId: "businessSetKeyTradesDialog",

			dialogButtons: {
				ok: {
					text: "确定",
					"class": "btn btn-primary",
					click: function() {
						var view = this.get("context");
						view.send("setTrade");
					}
				},
				cancel: {
					text: "取消",
					"class": "btn",
					click: function() {
						this.closeDialog();
					}
				}
			},

			/*
				列配置
			*/
			perfColumns: Ember.computed(function(){
				var columns = [
					{
						headerText: "请求标识",
						dataKey: "uri",
						width: 350,
						ensurePxWidth:true,
						allowSort: false,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								var data = args.row.data;
								var value = data.uri;
								var $item = $('<div class="column-summary"></div>').appendTo(args.$container);
								$item.html(APM.util.escape(value));
								args.$container.attr("title",value);
								return true;
							}
						}
					},
					{
						headerText: "IP",
						dataKey:"ip",
						width: 120,
						ensurePxWidth:true,
						allowSort: false,
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "吞吐量",
						dataKey:"performance.system/throughput/total",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "总时长",
						dataKey:"performance.system/response_time/total",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "响应时间",
						dataKey:"performance.system/response_time/avg",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "最快",
						dataKey:"performance.system/response_time/min",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "最慢",
						dataKey:"performance.system/response_time/max",
						_fmtType: "transform_time",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "流量",
						dataKey:"performance.system/request_size/total",
						_fmtType: "transform_flow",
						cellFormatter: APM.util.indicatorCellFormatter
					},
					{
						headerText: "错误数",
						dataKey:"performance.system/error/count",
						cellFormatter: APM.util.indicatorCellFormatter
					}
				];
				if(!this.get("auth.isNormal")){
					columns.push({
						headerText: "",
						width: 50,
						allowSort: false,
						ensurePxWidth: true,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								var ctrl = this.get("controller");
								var data = args.row.data;

								var cb;
								if(data.key) {
									cb = $('<button class="btn btn-mini" type="button" title="修改关键交易"><i class="icon-edit"/></button>');
								}else {
									cb = $('<button class="btn btn-mini" type="button" title="设置关键交易"><i class="icon-map-marker"/></button>');
								}
					
								cb.appendTo(args.$container).on("click",function(){
									ctrl.set("resourceId", data.id);
									var dialog = Broada.getView(ctrl.get("dialogId"));
									ctrl.requireResourceApdex();
									dialog.openDialog();
								});

								return true;
							}
						}
					});
				}
				return columns;
			}),

			performances: Ember.A(),

			tradesAdapterUrl: "trades/performances/total",

			pageIndex: 0,

			pageSize: 20,

			keyWord: "",

			orderBy: "system/response_time/total",

			desc:true,

			orderByTop: 100,

			getRequireParams: function(){
				return {
					appId: this.get("appId")
				};
			},

			/*
				向服务端请求某一小时内的详细性能数据
			*/
			requirePerformances: function(){
				var ctrl = this,
					store = this.container.lookup("store:apm");

				var startDate = this.get("startDate"),
					endDate = this.get("endDate");

				var params = Ember.merge(this.getRequireParams(), {
					orderBy: this.get("orderBy"),
					top: this.get("orderByTop"),
					desc: this.get("desc"),
					keyWord: this.get("keyWord"),
					pageIndex: this.get("pageIndex"),
					pageSize: this.get("pageSize"),
					startDate: +startDate,
					endDate: +endDate,
					tradeIp:this.get("tradeIp"),
					tradeProto:this.get("tradeProto")
				});
				if( isLocalDebugModel ){
					delete params.startDate;
					delete params.endDate;
					delete params.orderBy;
					delete params.top;
					delete params.pageSize;
				}

				return store.ajax("GET", this.get("tradesAdapterUrl"), params)
				.then(function(response){
					var performances = Ember.A(response['result']);

					performances.forEach(function(trade){
						trade.performance = trade.performance||{};
					});
					
					if (performances.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",20);
						ctrl.set("totalRows",0);
						ctrl.set("performances",performances);
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
						ctrl.set("performances",performances);
					}
					return response;
				});
			},

			requireResourceApdex: function() {
				var ctrl = this,
					resourceId = this.get("resourceId"),
					store = this.container.lookup("store:apm");
				return store.ajax("GET", "resource/"+resourceId+"/apdex_t", {
					resId : resourceId
				})
				.then(function(response){
					var keyTrade = Ember.A(response['result']);
					ctrl.set("tradeName", keyTrade.name);
					ctrl.set("apdex_t", keyTrade.apdex_t);
					return response;
				});
			},

			actions: {
				tradesAllUili:function(){
					var view = Broada.getView('tradesALLBselect');
				},
				search: function() {
					this.set("pageIndex", 0);
					this.requirePerformances();
				},

				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requirePerformances();
				},

				gridSorted: function(e, data, view){
					view.ensureControl(false);
					this.set("orderBy", data.column.dataKey.substr(12));
					this.set("desc", data.sortDirection=="descending"||undefined);
					this.requirePerformances();
				},

				setTrade: function(){
					var ctrl = this,
						store = this.container.lookup("store:apm");

					var resourceId = this.get("resourceId");
					var name = this.get("tradeName");
					if(!name){
						this.set("formTip", "交易名称不能为空!");
						return;
					}
					
					var apdex_t = this.get("apdex_t");
					if (apdex_t && !/^[\d]+$|^\d*\.\d+$/.test(apdex_t)) {
						this.set("formTip", "apdex_t值必须为整数或小数！");
						return;
					}

					this.set("formTip", null);

					store.ajax("PUT", "resource",{
						"resourceId" : resourceId,
						"name" : name,
						"apdex_t" : apdex_t
					}).then(function(response){
						alertTip("保存成功！", "success");

						ctrl.requirePerformances();
						
						ctrl.set("tradeName","");
						ctrl.set("apdex_t","");

						Broada.getView(ctrl.get("dialogId")).closeDialog();
					});
				},

				timeRangesChange: function(timeRange){
					this.set("startDate", timeRange.startDate);
					this.set("endDate", timeRange.endDate);
					this.requirePerformances();
				}
			}
		});

		return BusinessConfigThresholdComponent;
	}
);